package com.chengshi.shop.controller.mobile.order;

import com.chengshi.shop.controller.common.BaseController;
import com.chengshi.shop.model.member.Member;
import com.chengshi.shop.model.order.Order;
import com.chengshi.shop.model.order.OrderHistory;
import com.chengshi.shop.model.order.OrderItem;
import com.chengshi.shop.model.system.Express;
import com.chengshi.shop.service.express.ExpressService;
import com.chengshi.shop.service.member.MemberService;
import com.chengshi.shop.service.order.OrderHistoryService;
import com.chengshi.shop.service.order.OrderItemService;
import com.chengshi.shop.service.order.OrderPaymentService;
import com.chengshi.shop.service.order.OrderService;
import com.chengshi.shop.util.DateFormatUtil;
import com.chengshi.shop.util.EnumUtil;
import com.chengshi.shop.util.MessageUtils;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author xuxinlong
 * @version 2018年01月12日
 */
@Api(value = "order", tags ="管理员处理订单相关接口")
@RestController
@RequestMapping(value = "/mobile/manage")
public class ManageOrderController extends BaseController{
    @Resource
    private OrderService orderService;
    @Resource
    private MemberService memberService;
    @Resource
    private OrderItemService orderItemService;
    @Resource
    private OrderPaymentService orderPaymentService;
    @Resource
    private OrderHistoryService orderHistoryService;
    @Resource
    private ExpressService expressService;

    /**
     * 获取商城订单销量等数据
     * @return
     */
    @ApiOperation(value = "获取商城订单销量等数据")
    @GetMapping(value = "getShopReport")
    public HashMap<String, Object> getShopReport(){
        HashMap<String, Object> retMap = MessageUtils.success("查询成功");
        try {
            SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
            Calendar calendar = Calendar.getInstance();
            Date today = calendar.getTime();
            calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - 7);
            Date weekDay = calendar.getTime();
            retMap.put("waitPay", orderService.getOrderCountByStatus(EnumUtil.ORDER_STATUS.待付款.getValue().byteValue()));
            retMap.put("waitDelivery", orderService.getOrderCountByStatus(EnumUtil.ORDER_STATUS.待发货.getValue().byteValue()));
            retMap.put("waitReceipt", orderService.getOrderCountByStatus(EnumUtil.ORDER_STATUS.待收货.getValue().byteValue()));
            retMap.put("weekTradeOrder", orderService.getTradeOrderByFromDay(s.format(weekDay)));
            retMap.put("weekTradeAmount", orderService.getTradeAmountByFromDay(s.format(weekDay)));
            retMap.put("todayTradeOrder", orderService.getTradeOrderByThatDay(s.format(today)));
            retMap.put("todayNewMember", memberService.getNewMemberByThatDay(s.format(today)));
        } catch (Exception e) {
            retMap = MessageUtils.error(e.getMessage());
        }
        return retMap;
    }

    /**
     * 获取订单列表的ajax请求
     *
     * @param status
     * @return
     */
    @ApiOperation(value = "获取商城订单列表")
    @GetMapping(value = "/getOrderList")
    public HashMap<String, Object> getOrderList(@RequestParam(required = false) Byte status,@RequestParam(required = false) String startTime,
    @RequestParam(required = false) String endTime,@RequestParam(required = false) String orderNum) {
        HashMap<String, Object> retMap = MessageUtils.success();
        try {
            HashMap<String, Object> inMap = new HashMap<>();
            inMap.put("status", status);
            inMap.put("startTime", startTime);
            inMap.put("endTime", endTime);
            inMap.put("orderNum", orderNum);
            List<HashMap<String, Object>> orderList = new ArrayList<>();
            this.startPage();
            List<Order> list = orderService.getOrderList(inMap);

            for (Order order : list) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("orderId", order.getOrderId());
                map.put("orderNum", order.getOrderNum());
                map.put("status", order.getStatus());
                map.put("isEvaluate", order.getIsEvaluate());
                map.put("totalAmount", order.getTotalAmount().add(order.getPostage()));
                map.put("tradeAmount", order.getTotalAmount().add(order.getPostage()).subtract(order.getPayed()));
                Member member = memberService.getMemberByMemberId(order.getMemberId());
                map.put("memberName", member.getName());
                map.put("headImg", member.getHeadImg());

                // 订单明细
                List<OrderItem> itemList = orderItemService.getListByOrderId(order.getOrderId());
                List<HashMap<String, Object>> itemMapList = new ArrayList<>();
                for (OrderItem orderItem : itemList) {
                    HashMap<String, Object> itemMap = new HashMap<>();
                    itemMap.put("orderItemId", orderItem.getOrderItemId());
                    itemMap.put("goodsId", orderItem.getGoodsId());
                    itemMap.put("status", orderItem.getStatus());
                    itemMap.put("goodsName", orderItem.getGoodsName());
                    itemMap.put("specView", orderItem.getSpecView());
                    itemMap.put("goodsImage", orderItem.getGoodsImg());
                    itemMap.put("productId", orderItem.getProductId());
                    itemMap.put("price", orderItem.getPrice());
                    itemMap.put("productNum", orderItem.getProductNum());
                    itemMapList.add(itemMap);
                }
                map.put("orderItemList", itemMapList);
                orderList.add(map);
            }
            PageInfo pageList = new PageInfo<>(list);
            pageList.setList(orderList);
            retMap.put("data", pageList);
        } catch (Exception e) {
            return MessageUtils.error("获取订单列表失败!");
        }
        return retMap;
    }

    /**
     * 获取订单详情的ajax请求
     *
     * @param orderId
     * @return
     */
    @ApiOperation(value = "获取订单详情信息")
    @ApiImplicitParam(name = "orderId", value = "订单id", paramType = "query", dataType = "int", required = true)
    @GetMapping(value = "/getOrderDetail")
    public HashMap<String, Object> getOrderDetail(@RequestParam Integer orderId) {
        HashMap<String, Object> retMap = MessageUtils.success();
        try {
            Order order = orderService.getOrderByOrderId(orderId);
            if (order != null) {
                // 订单基本信息
                HashMap<String, Object> orderMap = new HashMap<>();
                orderMap.put("orderId", order.getOrderId());
                orderMap.put("orderNum", order.getOrderNum());
                //订单状态
                orderMap.put("status", order.getStatus());
                orderMap.put("isEvaluate", order.getIsEvaluate());

                orderMap.put("goodsAmount", order.getTotalAmount());
                orderMap.put("createTime", DateFormatUtil.formatDate(order.getCreateTime(), DateFormatUtil.FULL_DATE_FORMAT));
                orderMap.put("postage", order.getPostage());
                orderMap.put("totalAmount", order.getTotalAmount().add(order.getPostage()));
                orderMap.put("tradeAmount", order.getTotalAmount().add(order.getPostage()).subtract(order.getPayed()));
                orderMap.put("markText", order.getMarkText());
                // 收货地址
                orderMap.put("consignee", order.getConsignee());
                orderMap.put("address", order.getAddress());
                orderMap.put("mobile", order.getMobile());
                Member member = memberService.getMemberByMemberId(order.getMemberId());
                orderMap.put("memberName", member.getName());
                orderMap.put("headImg", member.getHeadImg());
                //订单赠品
                List<String> gifts = orderService.getOrderGiftList(order.getOrderId());
                orderMap.put("giftList", gifts);
                // 各种支付方式使用明细
                List<HashMap<String, Object>> orderPaymentMap = orderPaymentService.getOrderPayment(orderId);
                orderMap.put("orderPayment", orderPaymentMap);
                retMap.put("orderBase", orderMap);
                // 订单明细
                List<OrderItem> itemsList = orderItemService.getListByOrderId(order.getOrderId());
                List<HashMap<String, Object>> itemsMapList = new ArrayList<>();

                for (OrderItem orderItem : itemsList) {
                    HashMap<String, Object> itemMap = new HashMap<>();
                    itemMap.put("orderItemId", orderItem.getOrderItemId());
                    itemMap.put("goodsId", orderItem.getGoodsId());
                    itemMap.put("goodsName", orderItem.getGoodsName());
                    itemMap.put("specView", orderItem.getSpecView());
                    itemMap.put("status", orderItem.getStatus());
                    itemMap.put("goodsImage", orderItem.getGoodsImg());
                    itemMap.put("productId", orderItem.getProductId());
                    itemMap.put("price", orderItem.getPrice());
                    itemMap.put("productNum", orderItem.getProductNum());
                    itemsMapList.add(itemMap);
                }
                retMap.put("orderItem", itemsMapList);
            } else {
                return MessageUtils.error("没有找到该订单！");
            }
        } catch (Exception e) {
            return MessageUtils.error("获取订单详情失败！");
        }
        return retMap;
    }

    /**
     * 商家关闭订单
     * @param orderId
     * @return
     */
    @ApiOperation(value = "商家关闭订单")
    @ApiImplicitParam(name = "orderId", value = "订单Id", paramType = "query", dataType = "int")
    @PostMapping("/closeOrder")
    public HashMap<String, Object> closeOrder(@RequestParam Integer orderId){
        HashMap<String, Object> retMap = MessageUtils.success("关闭订单成功");
        try {
            Order order = orderService.getOrderByOrderId(orderId);
            if (order.getStatus() <= EnumUtil.ORDER_STATUS.待收货.getValue().byteValue()) {
                orderService.closeOrder(order, "商家", "商家关闭订单，交易关闭");
            } else {
                retMap = MessageUtils.error("该订单已无法关闭");
            }
        } catch (Exception e) {
            retMap = MessageUtils.error(e.getMessage());
        }
        return retMap;
    }

    /**
     * 获取订单历史记录
     * @param orderId
     * @return
     */
    @ApiOperation(value = "获取订单历史记录")
    @ApiImplicitParam(name = "orderId", value = "订单Id", paramType = "query", dataType = "int")
    @GetMapping(value = "/getOrderHistoryList")
    public HashMap<String, Object> getOrderHistoryList(@RequestParam Integer orderId) {
        HashMap<String, Object> retMap = MessageUtils.success();
        try {
            List<OrderHistory> list = orderHistoryService.getListByOrderId(orderId);
            retMap.put("list", list);
        } catch (Exception e) {
            return MessageUtils.error("获取数据列表失败!");
        }
        return retMap;
    }

    /**
     * 订单开始发货
     * @param orderId
     * @param expressNum
     * @param expressCode
     * @return
     */
    @ApiOperation(value = "订单开始发货填写快递")
    @PostMapping("/saveOrderDelivery")
    public HashMap<String, Object> saveOrderDelivery(@RequestParam Integer orderId, @RequestParam String expressNum, @RequestParam String expressCode){
        HashMap<String, Object> retMap = MessageUtils.success();
        try {
            Order order = orderService.getOrderByOrderId(orderId);
            order.setExpressNum(expressNum);
            order.setExpressCode(expressCode);
            boolean status = order.getStatus() == EnumUtil.ORDER_STATUS.待发货.getValue().byteValue()
                    || (order.getStatus() == EnumUtil.ORDER_STATUS.待收货.getValue().byteValue() && !order.getIsSign());
            if (status) {
                orderService.saveOrderDelivery(order);
            } else {
                retMap = MessageUtils.error("该订单状态暂时无法操作");
            }
        } catch (Exception e) {
            retMap = MessageUtils.error(e.getMessage());
        }
        return retMap;
    }

    /**
     * 获取快递公司列表
     * @return
     */
    @ApiOperation(value = "获取快递公司列表")
    @GetMapping("/getExpressList")
    public HashMap<String, Object> getExpressList(){
        HashMap<String, Object> retMap = MessageUtils.success();
        try {
            List<Express> expressList = expressService.getExpressList();
            retMap.put("list", expressList);
        } catch (Exception e) {
            retMap = MessageUtils.error(e.getMessage());
        }
        return retMap;
    }
}
